package cn.hzc.fortess.system.controller;

import cn.hzc.fortess.core.common.ResponseData;
import cn.hzc.fortess.core.common.annotion.RequestPermission;
import cn.hzc.fortess.system.search.ApiTokenSearch;
import cn.hzc.fortess.system.service.JwtTokenService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import springfox.documentation.annotations.ApiIgnore;

@Api(tags={"User API-Tokens管理"})
@Controller
@RequestMapping("/sam/apitoken")
public class ApiTokenController extends BaseController {

    private static final Logger log = LoggerFactory.getLogger(ApiTokenController.class);

    @Autowired
    private JwtTokenService jwtTokenService;

    @ApiIgnore
    @RequestMapping(value = "",method = RequestMethod.GET)
    public String index() {
        return buildToView("index.html");
    }

    @ApiOperation(value = "获取分页列表")
    @RequestMapping(value = "/list",method = RequestMethod.GET)
    @ResponseBody
    @RequestPermission("sam:apitoken:list")
    public Object page(ApiTokenSearch search) {
        return this.jwtTokenService.page(search);
    }


    /**
     * 清理过期
     */
    @ApiOperation(value = "清理过期Tokens")
    @RequestMapping(value = "/clean",method = RequestMethod.POST)
    @ResponseBody
    @RequestPermission("sam:apitoken:list")
    public Object cleanExpired() {

        int count =  jwtTokenService.cleanExpired();

        if(count==0){
            log.warn("过期ApiToken清理,影响行数:{}",count);
        }

        return ResponseData.success();
    }

    @ApiOperation(value = "删除Token")
    @RequestMapping(value = "/delete/{id}",method = RequestMethod.POST)
    @ResponseBody
    public ResponseData delete(@PathVariable(value = "id") Integer id) {
        this.jwtTokenService.delete(id);
        return ResponseData.success();
    }

    @Override
    protected String moduleName() {
        return "apitoken";
    }
}
